import 'package:dio/dio.dart';
import 'package:fluttertoast/fluttertoast.dart';
import './Api.dart';

/*
Dio封装 get，post  文件下載 down
 */
enum Method { get, post, down }

Future DioUtils(
    String urlString, Method method, Map<String, dynamic> map) async {
  try {
    Response response;
    //实例化Dio对象
    BaseOptions options = new BaseOptions(
      baseUrl: Api.baseUrlDevelop,
      connectTimeout: 5000,
      receiveTimeout: 3000,
    );
    Dio dio = new Dio(options);
    var type = method;
    switch (type) {
      case Method.get:
        print('get请求');
        response = await dio.get(urlString, queryParameters: map);
        break;
      case Method.post:
        print('post请求');
        FormData formData = FormData.fromMap(map);
        response = await dio.post(urlString, data: formData);
        break;
      case Method.down:
        print('文件下载');
        String savePath = map['savePath'];
        response = await dio.download(urlString, savePath);
        break;
    }
    print(response.data);
    print('response');
    //成功返回数据
    if (response.statusCode == 200) {
      Fluttertoast.showToast(msg: '取消成功');
      //json.decodez转化为dart对象
      if (response.data['status'] == 0) {
        return response.data;
        // 成功之后更新数据
        // this._getData();
      } else {
        Fluttertoast.showToast(msg: response.data.result);
      }
    } else {
      throw Exception('接口异常了');
    }
  } catch (e) {
    return print(e);
  }
}
